 /* On{X} Script: Stop WiFi when I leave home. Start it when I'm back.
  *
  * Developer: Gaurav Nandwani
  *
  * Description:
  *
  * This rule monitors phone's  location using defined region by 
  * latitude & longitude. It turns off WiFi when phone (you) exit the
  * region and turns it back on when phone (you) enter back in to the 
  * region.
  * 
  * Usage:
  * 
  * Change the values "location" variable:
  * 
  * name	    - Name of the location.
  * latitude	- Latitude of the location. 
  * longitude   - Longitude of the location.
  *
  * You can use Google Maps or Bing Maps to determine the latitude & 
  * longitude of your home.
  */

// Initializing variables 

var location = { name : "home", latitude : "12.683215", longitude : "87.165527"} ;

// End of variables initializing 

console.log("Started script: Stop WiFi when I leave " + location.name + ". Start it when I'm back.");

// create a geo region for the trigger to take place at
var region = device.regions.createRegion({
    latitude: parseFloat(location.latitude, 10),
    longitude: parseFloat(location.longitude, 10),
    name: location.name,
    radius: 500
});

// starting WiFi when entering home
region.on("enter", function () {
    // enable Wi-Fi
    if (!device.network.wifiEnabled) { 
        device.network.wifiEnabled = true; 
    }
    if (device.network.status.isWifiOn) {
        console.info('entered home: enabled WiFi');
    }
    else {
        console.error('entered home: BUT failed to enable WiFi');
    }
});

region.on("exit", function () {
    // disable Wi-Fi
    if (device.network.wifiEnabled) { 
        device.network.wifiEnabled = false; 
    }
    if (!device.network.status.isWifiOn) {
        console.info('exited home: disabled WiFi');
    }
    else {
        console.error('exited home: BUT failed to disable WiFi');
    }    
});

// start monitoring on the region
device.regions.startMonitoring(region);
console.log("Completed script: Stop WiFi when I leave " + location.name + ". Start it when I'm back.");
